package com.ruyuan.seckilling.render.async.listener;

import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.common.message.PagePublishMessage;
import com.ruyuan.seckilling.render.async.BaseRenderPageListener;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.event.Event07SendPublishPageMessage;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_07_SEND_PUBLISH_MESSAGE;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(CHANNEL_07_SEND_PUBLISH_MESSAGE)
public class Event07Listener extends BaseRenderPageListener<Event07SendPublishPageMessage> {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Event07SendPublishPageMessage;
    }

    // 6、投递发布页面消息
    @Override
    protected void doThisStep(Event07SendPublishPageMessage event, PageRenderContext context) {
        Runnable task = () -> {
            String publishPageMessage = PagePublishMessage.builder()
                    .pageLogId(context.getPageLog().getId())
                    .staticPageId(context.getStaticPageId())
                    .staticPagePath(context.getStaticPagePath())
                    .build()
                    .toJsonString();
            rocketMQTemplate.syncSend(QueueKey.QUEUE_PUBLISH_PAGE, publishPageMessage);
            log.info("第7步，保存流水，发送一条发布页面的消息, message={}", publishPageMessage);
        };

        executorService.execute(CHANNEL_07_SEND_PUBLISH_MESSAGE, task);
    }
}
